<?php

/*
  Author:
  Project: EBBS
 *//* * ********************Description********************* */
include 'library/init.php';
include 'library/header.php';

$Day = date("Y-m-d H:i:s", time() - 1209600);

echo "<h1>Mest leste innlegg</h1>";
$VC = 1;
$sql = 'SELECT * FROM blogpost WHERE Deleted = 0 ORDER BY ViewCount DESC';
$sth = $db->prepare($sql);
$sth->execute();
while ($row = $sth->fetch()) {
    if ($VC <= 14) {
        if ($row['Created'] > $Day) {
            echo "$VC. ";
            echo "<a href='post.php?id={$row['BlogpostID']}'>{$row['Title']}</a><br/>";
            $VC +=1;
        }
    }
}

echo "<form method='post' action='index.php'><label for='sok'><font size='5'>
      <br>Søk etter blog</font></label><br>
      <input type='text' name='sok'/><input type='submit' value='SØK'/>
      </form>";

if (isset($_POST['sok'])) {
    $sql = 'SELECT * FROM user WHERE Username LIKE :sok ORDER BY Username';
    $sth = $db->prepare($sql);
    $sok = '%' . $_POST['sok'] . '%';
    $sth->bindParam(':sok', $sok);
    $sth->execute();
    while ($row = $sth->fetch()) {
        echo "<a href='blog.php?id={$row['UserID']}'>{$row['Username']}</a><br/>";
    }
}
echo "<h1>Mest kommenterte blogginlegg</h1>";
$sql = 'SELECT BlogpostID, Title FROM blogpost';
$sth = $db->prepare($sql);
$sth->execute();
$i = 0;
while ($row = $sth->fetch()) {
    $tittel = $row['Title'];
    $sql1 = 'SELECT * FROM comment WHERE BlogpostID = :blogpostid';
    $sth1 = $db->prepare($sql1);
    $sth1->bindParam(':blogpostid', $row['BlogpostID']);
    $sth1->execute();
    $row1 = $sth1->fetch();
    $i++;
    $count = $sth1->rowCount();
    $counter[$count] = $i;
    $arr[$i] = array($count, $tittel, $row['BlogpostID'], $row1['Created']);
}

arsort($arr);
arsort($counter);
$i = 0;
foreach ($counter as $count) {
    if ($i++ == 14)
        break;
    if ($arr[$count][3] > $Day)
        echo "<a href='post.php?id={$arr[$count][2]}'>{$arr[$count][1]} $count</a><br>";
}
echo "<h1>Topp bloggere</h1>";
$sql2 = 'SELECT * FROM blogpost';
$sth2 = $db->prepare($sql2);
$sth2->execute();
while ($row2 = $sth2->fetch()) {
    $views = 0;
    $comms = 0;
    $userid = $row2['UserID'];
    $sql3 = 'SELECT * FROM comment WHERE BlogpostID = :BlogpostID';
    $sth3 = $db->prepare($sql3);
    $sth3->bindParam(':BlogpostID', $row2['BlogpostID']);
    $sth3->execute();
    while ($row3 = $sth3->fetch()) {
        $comms++;
    } 
    $sql4 = 'SELECT * FROM user WHERE UserID = :UserID';
    $sth4 = $db->prepare($sql4);
    $sth4->bindParam(':UserID', $userid);
    $sth4->execute();
    $row4 = $sth4->fetch();
    $views = $row2['ViewCount'];
    $top[$userid] = array($row4['Username'],$views, $comms);
}


arsort($top);
foreach ($top as $topp => $usr) {
    echo "<a href='blog.php?id=$topp'>{$top[$topp][0]}</a><br>";
}

include 'library/sidebar.php';
include 'library/footer.php';

